// pages/goods/order/index.js
var util = require('../../../utils/util.js')
import Toast from 'tdesign-miniprogram/toast/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    details: {},
    confirmBtn: {
      content: '确定',
      variant: 'base'
    },
    dialogKey: '',
    showConfirm: false,
    showWarnConfirm: false,
    showTooLongBtnContent: false,
    showMultiBtn: false,
    address: null,
    order: {
      order_no: '',
      order_status: 1,
      product_no: '',
      product_count: 1,
      order_amount_total: 1,
      logistics_fee: '',
      address_id: '',
      remarks: '',
      user_openid: '',
      delivery_time: '',
      gategory: '',
      size: '',
      order_settlement_time: ''
    },
    count: 1, //数量
    unit_price: 7.88, //单价
    total_price: 0, //总价
    freight: 0, // 运费
    inventory: 100, //库存
    gategoryValue: 0,
    gategory: [],
    gategoryVisible: false,
  },
  showDialog(e) {
    const {
      key
    } = e.currentTarget.dataset;
    console.log(key)
    this.setData({
      [key]: true,
      dialogKey: key
    });
  },

  closeDialog() {
    const {
      dialogKey
    } = this.data;
    this.setData({
      [dialogKey]: false
    });
  },
  confirmDialog() {
    const {
      dialogKey
    } = this.data;
    this.setData({
      [dialogKey]: false
    });
    this.submit()
  },
  chooseAddress() {
    wx.navigateTo({
      url: '/pages/me/address/list/index',
    })
  },
  calTotalPrice() {
    let total_price = this.data.details.price * this.data.order.product_count
    total_price = (Math.floor(total_price * 100) / 100).toFixed(2)

    this.setData({
      total_price
    })

    let _this = this
    // console.log(total_price,this.data.details.free_shipping)
    if (total_price >= this.data.details.free_shipping) {
      // console.log('达到免运费标准')
      this.setData({
        freight: 0,
        'order.logistics_fee': 0
      })
    } else {
      this.setData({
        freight: _this.data.details.freight,
        'order.logistics_fee': _this.data.details.freight,
      })
    }

    // console.log('商品总额==>',total_price)
    // console.log('运费==>',this.data.freight)

    if (total_price > 0) total_price = parseFloat(total_price) + parseFloat(this.data.freight)
    total_price = (Math.floor(total_price * 100) / 100).toFixed(2)

    this.setData({
      'order.order_amount_total': total_price
    })
    // console.log('总=>',this.data.order.order_amount_total)
  },
  gategoryOnChange(e) {
    this.setData({
      gategoryValue: e.detail.value
    });
  },
  onColumnChange(e) {
    console.log('picker pick:', e);
  },
  onPickerChange(e) {
    let _this = this

    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;

    console.log('picker change:', e.detail);
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: value.join(' '),
      'order.gategory': _this.data.details.gategory[value]
    });
  },

  onPickerCancel(e) {
    const {
      key
    } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  ongategoryPicker() {
    console.log('选择分类')
    this.setData({
      gategoryVisible: true
    });
  },
  remarksChange(e) {
    const {
      value
    } = e.detail;
    // console.log(value)
    this.setData({
      'order.remarks': value
    })
  },
  handleChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      'order.product_count': value,
    });
    this.calTotalPrice()
  },
  check() {
    let msg = ''
    if (this.data.order.address_id == '') {
      msg = '请添加收获地址'
    } else if (this.data.order.product_count == 0) {
      msg = '商品数量不能为0'
    }
    if (msg != '') {
      Toast({
        context: this,
        selector: '#t-toast',
        message: msg,
        theme: 'error',
      });
      return false
    }
    return true
  },
  submit() {
    if (!this.check()) return
    let order = this.data.order
    order.order_no = util.wxuuid()
    order.order_settlement_time = new Date()
    order.order_status = 5
    console.log('订单信息：', order)
    order['flag'] = 'add'
    wx.cloud.callFunction({
      name: 'updateOrder',
      data: order
    }).then(res => {
      console.log('订单提交成功', res)
      if (res.result.data.errMsg.includes("ok")) {
        setTimeout(() => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: `下单成功`,
            theme: 'success',
          });
        }, 500)

        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/goods/order-list/index',
          })
        }, 1000)
      }
    }).catch(error => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '出错了',
        theme: 'error',
      });
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.calTotalPrice()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  getAddress() {
    let _this = this
    let address = wx.getStorageSync('address')
    let cntAddressIndex = wx.getStorageSync('cntAddressIndex')
    if (!cntAddressIndex) {
      cntAddressIndex = 0
      wx.setStorageSync('cntAddressIndex', 0)
    }
    if (!address) {
      wx.cloud.callFunction({
        name: 'getAddress',
      }).then(res => {
        console.log('数据库address', res.result.data.data[0])
        if (res.result.data.data[0]) {
          wx.setStorageSync("address", res.result.data.data)
          address = res.result.data.data[cntAddressIndex]
          _this.setData({
            address,
            'order.address_id': address._id,
            'order.user_openid': address.user_openid
          })
        } else {
          _this.setData({
            address: null,
            'order.address_id': ''
          })
        }
      })
    } else {
      console.log('本地存在地址')
      address = address[cntAddressIndex]
      _this.setData({
        address,
        'order.address_id': address._id,
        'order.user_openid': address.user_openid
      })
    }
    console.log('当前地址', address)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddress()

    let _this = this
    let details = wx.getStorageSync("CntGood")

    let gategory = []
    for (let i = 0; i < details.gategory.length; i++) {
      gategory.push({
        label: details.gategory[i],
        value: i
      });
    }


    this.setData({
      freight: details.freight,
      details,
      gategory,
      'order.gategory': details.gategory[0],
      'order.product_no': details._id
    })

    this.calTotalPrice()
    console.log('details', details)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})